/**
 * Created by samsung on 2015/3/26.
 */
(function ($, window, document) {

    var totalnum = $("#totalnum");
    var totalprice = $("#totalprice");

    $("#chk_all").click(function() {
        var sum = 0;
        var num = 0;
        if (this.checked) {
            $("input[name='chk_list']").each(function () {
                this.checked = true;
                var price = parseFloat($(this).closest("tr").find("span").html());
                var count = parseInt($(this).closest("tr").find("input[class*=goodsnum]").val());
                num += count;
                sum += price * count;
            });
            totalnum.html(num);
            totalprice.html(sum.toFixed(2));
        } else {
            $("input[name='chk_list']").each(function () {
                this.checked = false;
            });
            totalnum.html(0);
            totalprice.html(0.00);
        }
    });

    $("input[name='chk_list']").click(function() {
        var price = parseFloat($(this).closest("tr").find("span").html());
        var count = parseInt($(this).closest("tr").find("input[class*=goodsnum]").val());
        var subprice = price * count;
        if (this.checked) {
            totalnum.html(parseInt(totalnum.html()) + count);
            totalprice.html((parseFloat(totalprice.html()) + subprice).toFixed(2));
        } else {
            totalnum.html(parseInt(totalnum.html()) - count);
            totalprice.html((parseFloat(totalprice.html()) - subprice).toFixed(2));
        }
    });

    $(".add").click(function() {
        // 单项商品数量
        var count = $(this).parent().find("input");
        // 商品单价
        var price = $(this).closest("td").find("span");
        // 是否选中
        var selected = $(this).closest("tr").find("input[name='chk_list']").is(":checked");
        // 设置单项商品数量
        count.val(parseInt(count.val()) + 1);
        if (selected) {
            // 设置商品总数
            totalnum.html(parseInt(totalnum.html()) + 1);
            // 设置商品总价
            totalprice.html((parseFloat(totalprice.html()) + parseFloat(price.html())).toFixed(2));
        }
    });

    $(".reduce").click(function() {
        // 单项商品数量
        var count = $(this).parent().find("input");
        // 商品单价
        var price = $(this).closest("td").find("span");
        // 是否选中
        var selected = $(this).closest("tr").find("input[name='chk_list']").is(":checked");

        var n = parseInt(count.val());
        if (n > 1) {
            // 设置单项商品数量
            count.val(n - 1);
            if (selected) {
                // 设置商品总数
                totalnum.html(parseInt(totalnum.html()) - 1);
                // 设置商品总价
                totalprice.html((parseFloat(totalprice.html()) - parseFloat(price.html())).toFixed(2));
            }
        }
    });

})(jQuery, window, document);